﻿using AutoMapper;
using ERPSystem.Common.Domains.Delivergoods;
using ERPSystem.Common.Domains.SalesOrderCommom;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using Yitter.IdGenerator;

namespace SalesManagementWrite.API.SalesManagementWrites.Deliverynotice
{
    public class DeliverynoticeCreateHandler : IRequestHandler<DeliverynoticeCreateCommon,Result>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<Shippingnote> shippingnoteRepository;

        public DeliverynoticeCreateHandler(IMapper mapper, IBaseRepository<Shippingnote> shippingnoteRepository)
        {
            _mapper = mapper;
            this.shippingnoteRepository = shippingnoteRepository;
        }


        /// <summary>
        /// 发货通知单新增接口
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DeliverynoticeCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var salesOrder = _mapper.Map<Shippingnote>(request);
                salesOrder.DocumentNumber = YitIdHelper.NextId().ToString();
                salesOrder.Warehouseentry = YitIdHelper.NextId().ToString();
                salesOrder.DocumentNumber = "FHDD"+(YitIdHelper.NextId().ToString().Substring(0, 8));
                salesOrder.CreatedOwnerId = "张三";
                salesOrder.CreatedTime = DateTime.Now;
                salesOrder.Auditor = "李四";
                salesOrder.AuditDate = DateTime.Now;
                var list = await shippingnoteRepository.Add(salesOrder);
                if (list > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                else
                {
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
